<template>
  <div>
    <el-row>
      <el-col :span="20">
        <el-input size="mini" placeholder="输入关键字进行过滤" v-model="filterText" style="padding-bottom: 5px;"></el-input>
      </el-col>
      <el-col :span="4">
        <el-button size="mini" title="刷新" @click="handleRefresh" icon="el-icon-refresh" circle style="margin-left: 5px;"></el-button>
      </el-col>
    </el-row>
      <el-tree ref="tree" :show-checkbox="showCheckBox" :data="formatData" @node-click="handleNodeClick" :expand-on-click-node="false"
        :default-expanded-keys="rid"  @check-change="handleCheckChange" :default-checked-keys="selected" highlight-current node-key="id" :filter-node-method="filterNode" :props="{
      label: 'name',
    }"></el-tree>
  </div>
</template>
<script>
  import * as service from "@/api/crud.base";
  import TreeUtil from '@/libs/tree'
  export default {
    props:{
      data:{
        type:Array
      },
      showCheckBox:{
        type:Boolean
      },
      selected:{
        type:Array
      }
    },
    data() {
      return {
        filterText: '',
      }
    },
    methods: {
      handleNodeClick(data) {
        this.$emit('node-click', data)
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      handleRefresh(){
        this.$emit("refresh");
      },
      handleCheckChange(data, checked, indeterminate){
        this.$emit('check-change',data,checked,indeterminate);
      }
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
    },
    computed: {
      formatData() {
        var tree = TreeUtil.arrayTransTree(this.data, 'pid', 'children');
        return tree;
      },
      rid(){
        let id=[];
        for(let record of this.data){
          if(!record.pid){
            id[0]=record.id
            break;
          }
        }
        return id;
      }
    },
  }
</script>
